package cn.itcast.wanxinp2p.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;

@Component
public class AuthFilter implements GlobalFilter, Ordered {
    @Resource
    RedisTemplate<String,String> redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println(exchange.getRequest().getPath()+">>>>>>>>>");
//        ServerHttpRequest request = exchange.getRequest();
//        System.out.println((redisTemplate.opsForValue().get("111111")==null)+"keyeyeyeeeee");
//        List<String> list= request.getHeaders().get("token");
//        if(exchange.getRequest().getPath().toString().contains("/consumer"))
//        if(list.size()<=0)
//        {
//            ServerHttpResponse response = exchange.getResponse();
//            JSONObject message = new JSONObject();
//            message.put("status", 401);
//            message.put("data", "未登录");
//            byte[] bits = message.toJSONString().getBytes(StandardCharsets.UTF_8);
//            DataBuffer buffer = response.bufferFactory().wrap(bits);
//            response.setStatusCode(HttpStatus.UNAUTHORIZED);
//            //指定编码，否则在浏览器中会中文乱码
//            response.getHeaders().add("Content-Type", "text/plain;charset=UTF-8");
//            return response.writeWith(Mono.just(buffer));
//
//        }
//        String token = list.get(0);
//        String aaa = redisTemplate.opsForValue().get(token);
//        System.out.println(aaa+"token.....");
//
//
////        Map<String, String> jsonToken = new HashMap<>
////                (oauth2Authentication.getOAuth2Request().getRequestParameters());
////        String value = EncryptUtil.encodeUTF8StringBase64(JSON.toJSONString(jsonToken));
////        exchange.getRequest().getQueryParams().set("jsonToken",value);
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
